package com.fileutils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2019/4/23.
 */

public class StringUtils {
    /**
     * 去除换行、制表等符号
     * @param str
     * @return
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * MAC地址格式化
     * 类似12ae5bac34c4中间无分隔符，需要在中间加入分隔符(:或者-),最终效果：12:ae:5b:ac:34:c4
     * @param address
     * @param split
     * @return
     */
    public static String formatMac(String address, String split){
        String mac=address.substring(4,16);
        String regex = "[0-9a-fA-F]{12}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(mac);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("mac format is error");
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 12; i++) {
            char c = mac.charAt(i);
            sb.append(c);
            if ((i & 1) == 1 && i <= 9) {
                sb.append(split);
            }
        }
        return sb.toString();
    }

    /**
     * MAC地址格式化
     * 类似12:ae:5b:ac:34:c4或者12-ae-5b-ac-34-c4中间有分隔符，需要去掉分隔符(:或者-),最终效果：12ae5bac34c4
     * @param mac
     * @return
     */
    public static String formatMac1(String mac) {
        String regex = "(([a-f0-9]{2}:)|([a-f0-9]{2}-)){5}[a-f0-9]{2}";
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(mac);

        if (!matcher.matches()) {
            throw new IllegalArgumentException("mac format is error");
        }
        return mac.replaceAll("[:-]", "");
    }
}